﻿using Engine;
using Game;
using GameEntitySystem;
using TemplatesDatabase;

namespace SAGhoul
{
	public class SubsystemSplittingThrowableBlockBehavior : SubsystemBlockBehavior   //分裂射击
	{
		public SubsystemAudio m_subsystemAudio;              // 音频子系统
		public SubsystemProjectiles m_subsystemProjectiles;  // 投射物子系统
		public Game.Random m_random = new();     // 随机数生成器

		public override int[] HandledBlocks => new int[0];   // 处理的方块类型（空数组表示处理所有类型）

		public override bool OnAim(Ray3 aim, ComponentMiner componentMiner, AimState state)  // 分裂射击行为
		{
			switch (state)
			{
				case AimState.InProgress:  // 瞄准进行中状态
				{
					// 设置瞄准手部角度（从原版3.2减少到1.0以加快瞄准速度）
					componentMiner.ComponentCreature.ComponentCreatureModel.AimHandAngleOrder = 0.5f;

					// 获取当前手持方块的类型
					Block block2 = BlocksManager.Blocks[Terrain.ExtractContents(componentMiner.ActiveBlockValue)];
					ComponentFirstPersonModel componentFirstPersonModel = componentMiner.Entity.FindComponent<ComponentFirstPersonModel>();

					if (componentFirstPersonModel != null)
					{
						// 显示准星
						componentMiner.ComponentPlayer?.ComponentAimingSights.ShowAimingSights(aim.Position, aim.Direction);
						// 设置第一人称物品偏移
						componentFirstPersonModel.ItemOffsetOrder = new Vector3(0f, 0.35f, 0.17f);
					}
					break;
				}

				case AimState.Completed:  // 瞄准完成状态（发射时刻）
				{
					// 计算发射起点位置（眼睛位置向右偏移0.4单位）
					Vector3 vector = componentMiner.ComponentCreature.ComponentCreatureModel.EyePosition + (componentMiner.ComponentCreature.ComponentBody.Matrix.Right * 0.4f);
					// 计算发射方向向量
					var v = Vector3.Normalize(vector + (aim.Direction * 10f) - vector);

					// 检查是否有物品栏
					if (componentMiner.Inventory == null)
					{
						break;
					}

					// 获取当前手持物品信息
					int activeSlotIndex = componentMiner.Inventory.ActiveSlotIndex;
					int slotValue = componentMiner.Inventory.GetSlotValue(activeSlotIndex);
					int slotCount = componentMiner.Inventory.GetSlotCount(activeSlotIndex);
					int num = Terrain.ExtractContents(slotValue);
					Block block = BlocksManager.Blocks[num];

					// 检查是否有物品可发射
					if (slotCount > 0)
					{
						// 计算基础投射速度
						float projectileSpeed = block.GetProjectileSpeed(slotValue);

						// 如果是玩家，考虑力量因子影响速度
						if (componentMiner.ComponentPlayer != null)
						{
							projectileSpeed *= (0.5f * ((componentMiner?.ComponentFactors?.StrengthFactor ?? 1f) - 1f)) + 1f;
						}

						// 计算基础速度向量（角色速度+发射方向速度）
						Vector3 baseVelocity = componentMiner.ComponentCreature.ComponentBody.Velocity + v * projectileSpeed;
						bool anyProjectileCreated = false;  // 改为检查是否有任意投射物创建成功

						// 创建8个呈扇形分布的投射物
						for (int i = 0; i < 8; i++)
						{
							Vector3 offset = Vector3.Zero;         // 位置偏移量
							Vector3 velocityVariation = Vector3.Zero;  // 速度变化量

							// 中心投射物 (i = 0)
							if (i == 0)
							{
								offset = Vector3.Zero;
								velocityVariation = Vector3.Zero;
							}
							// 水平方向扇形分布 (i = 1-4)
							else if (i <= 4)
							{
								// 水平偏移量（从-0.45到0.45，间隔0.3单位）
								float horizontalOffset = (i % 2 == 0) ? -0.3f * ((i + 1) / 2) : 0.3f * (i / 2);
								offset = componentMiner.ComponentCreature.ComponentBody.Matrix.Right * horizontalOffset;
								velocityVariation = componentMiner.ComponentCreature.ComponentBody.Matrix.Right * horizontalOffset * 1.5f;
							}
							// 垂直方向扇形分布 (i = 5-7)
							else
							{
								// 垂直偏移量（从-0.3到0.3，间隔0.3单位）
								float verticalOffset = (i % 2 == 0) ? -0.2f * ((i - 3) / 2) : 0.2f * ((i - 3) / 2);
								offset = componentMiner.ComponentCreature.ComponentBody.Matrix.Up * verticalOffset;
								velocityVariation = componentMiner.ComponentCreature.ComponentBody.Matrix.Up * verticalOffset * 1.5f;
							}

							// 计算最终位置和速度
							Vector3 position = vector + offset;
							Vector3 velocity = baseVelocity + velocityVariation + m_random.Vector3(0f, 0.5f);  // 添加随机速度变化

							// 发射投射物
							Projectile projectile = m_subsystemProjectiles.FireProjectile(
								slotValue,
								position,
								velocity,
								m_random.Vector3(3f, 5f),  // 随机旋转
								componentMiner.ComponentCreature);

							// 只要有任意一个投射物创建成功就标记为true
							if (projectile != null)
							{
								anyProjectileCreated = true;
							}
						}

						// 只要有任意投射物创建成功，就执行后续操作
						if (anyProjectileCreated)
						{
							// 从物品栏移除1个物品
							componentMiner.Inventory.RemoveSlotItems(activeSlotIndex, 1);
							// 播放投掷音效
							m_subsystemAudio.PlaySound("Audio/Throw", m_random.Float(0.2f, 0.3f), m_random.Float(-0.2f, 0.2f), aim.Position, 2f, autoDelay: true);
							// 触发矿工动作
							componentMiner.Poke(forceRestart: false);
						}
					}
					break;
				}
			}
			return false;
		}
		public override bool OnHitAsProjectile(CellFace? cellFace, ComponentBody componentBody, WorldItem worldItem)
		{
			if (componentBody?.Entity?.FindComponent<ComponentSAGhouls>() != null && worldItem is Projectile projectile)
			{
				projectile.AttackPower *= 20f;
			}
			return base.OnHitAsProjectile(cellFace, componentBody, worldItem);
		}
		// 加载子系统
		public override void Load(ValuesDictionary valuesDictionary)
		{
			m_subsystemAudio = Project.FindSubsystem<SubsystemAudio>(throwOnError: true);
			m_subsystemProjectiles = Project.FindSubsystem<SubsystemProjectiles>(throwOnError: true);
			base.Load(valuesDictionary);
		}
	}
}